package com.seal.tsms.school.controller;

import com.seal.tsms.base.controller.BaseController;
import com.seal.tsms.base.service.BaseService;
import com.seal.tsms.school.entity.EducationInfo;
import com.seal.tsms.school.entity.StudentInfo;
import com.seal.tsms.school.service.EducationInfoService;
import com.seal.tsms.school.service.StudentInfoService;
import org.hibernate.criterion.DetachedCriteria;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangwen on 2016/1/22.
 */
@Controller
@RequestMapping("/school/educationInfo")
public class EducationController extends BaseController<EducationInfo,String>{

    @Override
    @Autowired
    @Qualifier("educationInfoServiceImpl")
    public void setSelfService(BaseService<EducationInfo, String> selfService) {
        super.setSelfService(selfService);
    }

    @RequestMapping(value = "/addEducation",method = RequestMethod.GET)
    public String create(){
        return "/school/educationInfo/add";
    }
    @RequestMapping(value = "/addEducation",method = RequestMethod.POST)
    public String save(@ModelAttribute("educationInfo")EducationInfo educationInfo, RedirectAttributes att){
          getSelfService().save(educationInfo);
        att.addAttribute("id",educationInfo.getId());
        att.addFlashAttribute("message","一条记录添加成功！");
        return "redirect:/school/educationInfo/show.do";

    }
    @RequestMapping(value = "/show")
    public String show(@RequestParam String id, ModelMap modelMap) {
        modelMap.addAttribute("educationInfo", getSelfService().get(id));
        return "/school/educationInfo/show";
    }
    @RequestMapping(value = "/importxls",method = RequestMethod.GET)
    public String toImportxls(){
        return "school/educationInfo/import";
    }
    @RequestMapping(value = "/importxls",method = RequestMethod.POST)
    public String importxls(@RequestParam(value = "file")MultipartFile file, HttpServletRequest request,RedirectAttributes attr){
        String path=request.getServletContext().getRealPath("/static/xls");
        String fileName=file.getOriginalFilename();
        File targetFile=new File(path,fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
            InputStream inputXML=new BufferedInputStream(getClass().getResourceAsStream("/xml/xls-template/educationinfo.xml"));
            XLSReader mainReader= ReaderBuilder.buildFromXML(inputXML);
            InputStream inputXLS=new BufferedInputStream(new FileInputStream(targetFile));
            List<EducationInfo>  educationInfos=new ArrayList<EducationInfo>();
            Map beans=new HashMap();
            beans.put("educationinfos",educationInfos);
            ReaderConfig.getInstance().setSkipErrors(true);
            ReaderConfig.getInstance().setUseDefaultValuesForPrimitiveTypes(true);
            XLSReadStatus readStatus=mainReader.read(inputXLS,beans);
            ((EducationInfoService)getSelfService()).saveList(educationInfos);
            attr.addFlashAttribute("msg","导入成功");
        }catch (Exception e){
            attr.addFlashAttribute("msg","导入失败");
            log.error("导入失败",e);
        }
        return "redirect:/school/educationInfo/ok.do";
    }
    @RequestMapping(value = "/ok")
    public String ok(){
        return "school/educationInfo/ok";
    }
    @RequestMapping(value = "/exportXLs")
    public String exportXLs(HttpServletRequest request,RedirectAttributes attr) {
        InputStream is = null;
        OutputStream os = null;
        try {
            List<EducationInfo> educationInfos= (List<EducationInfo>) getSelfService().list(DetachedCriteria.forClass(EducationInfo.class),null);
            is=getClass().getResourceAsStream("/xml/xls-template/educationInfo-temp.xls");
            os=new FileOutputStream("d:/git/formulas_output.xls");
            Context context=new Context();
            context.putVar("educationInfos",educationInfos);
            JxlsHelper.getInstance().processTemplateAtCell(is,os,context,"学员教育信息!A1");
            attr.addFlashAttribute("msg","导出成功");
        } catch (Exception e) {
            log.error("error",e);
            attr.addFlashAttribute("msg","导出失败");
        }finally {
            try {
                os.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "redirect:/school/educationInfo/ok.do";
        }
    }
}
